#-------------------------------------------------------------------------------
# Name:        Menu
# Purpose:
#
# Author:      Pablo
#
# Created:     10/02/2012
# Copyright:   (c) Monxcleyr Productions 2012
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import pygame, config, os

class Menu:
  def __init__(self, menuSurface, filename, common, sound, music, debug):

    self.menuSurface = menuSurface
    self.menu_item = []
    self.count = 0 # counts the frames for an animated background
    conf = config.Config()
    self.configfile = filename
    conf.read(os.path.join("resources/configs/" + filename))
    self.bg = conf.getint_tuple('Graphics', 'bgcolor')
    self.debug = debug # debug class instance
    self.sound = sound
    self.music = music
    self.common = common
    self.settings = self.common.settings
    # Custom cursor
    self.mousevisable = conf.getboolean('Graphics', 'mousevisable')
    self.cursor = conf.get('Graphics', 'mousecustom')
    if self.cursor == 'None': self.cursor = None # Reset string to key word
    if self.cursor != None:
      self.cursor = pygame.image.load(os.path.join('resources/graphics/' + self.cursor))
      self.cursor.set_colorkey((255,0,255))
    self.musicloop = conf.get('Sounds', 'music')
    if self.musicloop == 'None':
      self.musicloop = None
    self.firstdraw = True # Just a variable for checking first time through draw loop

#-------------------------------------------------------------------------------

    # Background image loading
    bgimage = conf.get('Graphics', 'bgimage')
    if bgimage == 'None': bgimage = None #just making the string 'None' into the keyword None
    if bgimage != None:
      self.bgimage = pygame.image.load(os.path.join('resources/graphics/' + bgimage)).convert_alpha()
    else:
      self.bgimage = bgimage

#-------------------------------------------------------------------------------


    # Animated Background loading

    self.bganimated = conf.getboolean('Graphics', 'bganimated')

    # Load the frames if we have an animated screen
    if self.bganimated == True:
      bgdir = conf.get('Graphics', 'bgdirectory')
      bgdir = 'resources/graphics/' + bgdir
      self.bgframes, self.bgframecount = self.getFrames(bgdir)

#-------------------------------------------------------------------------------

    # Title image loading
    logoimage = conf.get('Graphics', 'logo')
    self.logopos = conf.getint_tuple('Graphics', 'logopos')# load uncentered position
    if logoimage == 'None': logoimage = None #just making the string 'None' into the keyword None
    if logoimage != None:
      self.logoimage = pygame.image.load(os.path.join('resources/graphics/' + logoimage)).convert_alpha()
      # center image:
      self.logopos = (self.logopos[0] - (self.logoimage.get_width() / 2), self.logopos[1] - (self.logoimage.get_height() / 2))
    else:
      self.logoimage = logoimage

#-------------------------------------------------------------------------------

    # Find number of menu options
    checking = 1
    count = 1
    while checking == 1:
      if conf.has_section("Option" + str(count)) == True:
        count += 1
      else:
        checking = 0

#-------------------------------------------------------------------------------

    # Load up the menu options
    for i in range(1, count):
      pos = conf.getint_tuple("Option" + str(i),"position")
      button = conf.get("Option" + str(i),"button")
      buttonhover = conf.get("Option" + str(i),"buttonhover")
      clicksound = conf.get("Option" + str(i), "clicksound")
      mode = conf.get("Option" + str(i), "mode")
      if clicksound == 'None':
        clicksound = None
      if conf.has_option("Option" + str(i), "link") == True:
        link = conf.get("Option" + str(i), "link")
      else:
        link = ''
      self.menu_item.append(MenuItem(i, pos, button, buttonhover, clicksound, mode, link))

#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------


  def draw(self, mouse, balloonmode=False):

    if self.firstdraw == True:
      if balloonmode:
        self.musicloop = 'balloon'
      self.debug.setRight("./resources/configs/" + self.configfile)
      pygame.mouse.set_visible(self.mousevisable)
      # Load music queue for menu if enabled
      if self.musicloop:
        if self.music.getCurrentLoop() != self.musicloop:
          self.music.loadQueue(self.musicloop)
          self.music.playQueue()
      self.firstdraw = False


    # This is boilerplate code for running the music queue.
    if self.musicloop:
      if pygame.mixer.music.get_busy() == 0:
        self.music.playQueue()

    self.mouse = mouse[0]
    self.mouseup = mouse[1]

    # Draw background stuff
    self.menuSurface.fill(self.bg)
    if self.bgimage != None and self.bganimated == False:
      self.menuSurface.blit(self.bgimage, (0,0))

    if balloonmode:
      if self.count == 1:
        self.menuSurface.fill((0,0,255))
      if self.count == 2:
        self.menuSurface.fill((255,0,0))
      if self.count == 3:
        self.menuSurface.fill((0,255,0))
      if self.count == 4:
        self.menuSurface.fill((255,255,0))
      if self.count == 5:
        self.menuSurface.fill((255,0,255))
      if self.count == 6:
        self.menuSurface.fill((0,255,255))
      self.count += 1
      if self.count >= 6:
        self.count = 0


    # Animated background
    if balloonmode == False:
      if self.bganimated == True:
        self.menuSurface.blit(self.bgframes[self.count], (0,0))
        self.count += 1 # interate counting variable
        if self.count == (self.bgframecount - 1):
          self.count = 0

    # Title image
    if self.logoimage != None:
      self.menuSurface.blit(self.logoimage, self.logopos)

    # Check buttons to draw, hovered or normal:
    hover = self.getHover() # find a seclected button, if any
    for mitem in self.menu_item: #Get each menu item from the list
      if hover == mitem.id:
        self.menuSurface.blit(mitem.buttonhover, mitem.pos)
      else:
        self.menuSurface.blit(mitem.button, mitem.pos)

    if self.cursor != None:
      self.menuSurface.blit(self.cursor, self.mouse)


    return self.menuSurface


  def getFrames(self, dirname):

    frames = []
    filecount = 0
    for root, dirs, files in os.walk(os.path.join(dirname)):
      for file in files:
        frames.append(pygame.image.load(os.path.join(root,file)).convert())
        filecount += 1
    return frames, filecount


  def getHover(self):

    """ Returns hovered option. 0 if none."""

    selected = 0

    for i in range(0, len(self.menu_item)):
      if self.menu_item[i].rect.collidepoint(self.mouse):
        selected = self.menu_item[i].id

    return selected


  def getSelected(self):

    """ Returns selected option. 0 if none."""

    selected = 0
    mode = 0

    if self.mouseup == 2:
      pressed = True
    else:
      pressed = False
    for i in range(0, len(self.menu_item)):
      if self.menu_item[i].rect.collidepoint(self.mouse) and pressed == True:
        self.sound.play(self.menu_item[i].sound, self.settings)
        selected = self.menu_item[i].id
        mode = self.menu_item[i].mode

    return selected, mode

  def reset(self):
    """Resets the menu so it operates properly next time it's used.
    Call after mode changes """
    self.firstdraw = True


class MenuItem:
  def __init__(self, id, pos, button, buttonhover, sound, mode, link):

    self.id = id
    self.pos = pos
    self.button = pygame.image.load(os.path.join('resources/graphics/' + button)).convert_alpha()
    self.buttonhover = pygame.image.load(os.path.join('resources/graphics/' + buttonhover)).convert_alpha()
    #center image:
    self.pos = (pos[0] - (self.button.get_width() / 2), pos[1] - (self.button.get_height() / 2))
    self.rect = self.get_rect()
    self.sound = sound
    self.mode = mode
    self.link = link

  def get_rect(self):
    return pygame.Rect(self.pos, (self.button.get_width(), self.button.get_height()))
